<template>
  <div class="box">
    <div class="box-header">{{ year }}年度账单</div>
    <div class="box-body" id="charts4"></div>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { onMounted, computed, ref, reactive } from 'vue'
interface seriesObj {
  name: string,
  value: number
}
// 接受父组件数据
const prop = defineProps({
  data: { type: Array, default: [] },
})
const year =ref('2025')
const yearData = computed(() => {
  return prop.data.filter(item=>{
    return year.value === item.time.split('-')[0]
  })
})

const dataFormatPie = (list, filed) => {
  // 分组
  const group = Object.groupBy(list, item => item[filed])
  const seriesObj={}
  for (const key in group) {
    const sum = group[key].reduce((total, item) => total + parseFloat(item.price), 0);
    seriesObj[key] = Math.round(sum * 100) / 100; // 四舍五入保留2位小数
  }
  return seriesObj
}

const option = computed(() => {
  return {
    tooltip: {},
    grid: {},
    xAxis: {
      type: 'category',
      data: Object.keys(series.value),
      axisLabel:{
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '',
        type: 'bar',
        data:Object.values(series.value),
      }
    ]
    }
})
const myChartDom = ref<any>(null)
const series = ref<any>([])
onMounted(() => {
  myChartDom.value = echarts.init(document.getElementById('charts4'));
  series.value = dataFormatPie(yearData.value, 'leave2')
  myChartDom.value.setOption(option.value);
})
</script>
<style scoped lang="scss">
.box {
  width: 100%;
  height: 100%;

  .box-header {
    width: 100%;
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    text-align: center;

  }

  .box-body {
    width: 100%;
    height: calc(100% - 50px);
    background: #fff;
  }
}
</style>
